跳到主要内容

生命周期钩子

旧的,组件的生命周期

当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:

组件挂载

class Welcome extends React.Component {
// 步骤1. constructor
constructor(props) {
super(props);
}

// 步骤2. static getDerivedStateFromProps
static getDerivedStateFromProps(props: any, state: any) {
return { ...props };
}

// 步骤4. componentDidMount
componentDidMount() {
// DOM加载完成,在这里执行需要执行的逻辑代码
}

// 步骤3. render
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

组件更新

class Welcome extends React.Component {
// 步骤1. static getDerivedStateFromProps
static getDerivedStateFromProps(props: any, state: any) {
// 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。
return { ...props };
}
// 步骤2. shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState) {
// 默认行为是 state 每次发生变化组件都会重新渲染。
return true;
}

// 步骤4. getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState) {
// 在最近一次渲染输出(提交到 DOM 节点)之前调用。
return true;
}

// 步骤5. componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot) {
// 会在更新后会被立即调用。首次渲染不会执行此方法。
}

// 步骤3. render
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

组件卸载

class Welcome extends React.Component {
// 步骤1. componentWillUnmount
componentWillUnmount() {
// 会在组件卸载及销毁之前直接调用。
}
}

其他生命周期

class Welcome extends React.Component {
componentDidCatch(error, info) {
// 此生命周期在后代组件抛出错误后被调用。
}
}

生命周期图谱

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/